package com.netsdk.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;



public class ScorketServer {
	
	//  创建一个单线程的 ExecutorService
    private final static ExecutorService executor = Executors.newSingleThreadExecutor();
	
	public static void main(String[] args) throws Exception {
		ServerSocket serverSocket = new ServerSocket(8091);
		try {
			service(serverSocket);
		} catch (Exception e) {
			service(serverSocket);
			System.out.println(e.getMessage());
		}
	}

	private static void service(ServerSocket serverSocket) throws Exception {
	 try {
			System.out.println("服务器已启动，等待客户端连接...");
		while (true) {
			Socket socket = serverSocket.accept();
			String hostAddress = socket.getInetAddress().getHostAddress();
			System.out.println("客户端连接成功：" + hostAddress);
//			String result = readString(socket);
            if (hostAddress.equals("127.0.0.1")){
            	SyncData syncData = new SyncData(socket);
    			Thread t2 = new Thread(syncData);
    			t2.start();
            }else {
            	socket.setSendBufferSize(65536*8);
				Test call = new Test(socket);
				Thread t1 = new Thread(call);
				t1.start();
			}
		}
		}catch (Exception e) {
				throw e;
		}
	}
	
    private static String readString(Socket socket) throws IOException {
        InputStream inputStream = socket.getInputStream();
        BufferedReader reader =new BufferedReader( new InputStreamReader(inputStream));
		// 提交一个任务来读取数据
        Future<String> future = executor.submit(() -> {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });
        try {
			// 提交一个任务来读取数据
            String result = future.get(5, TimeUnit.SECONDS);
            return result;
        } catch (TimeoutException e) {
            System.out.println("Reading timed out.");
            future.cancel(true);// 取消任务
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            try {
//                reader.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
    }
        return null;
    }
}
